/* 
 * File:   IndexHandler.cpp
 * Author: taylor
 * 
 * Created on November 7, 2012, 2:31 PM
 */

#include "IndexHandler.h"

/**
 * Default constructor uses an AVL tree as its structure
 */
IndexHandler::IndexHandler() {
    _tree = new AVLTreeAdapter;
}

/**
 * Constructor for IndexHandler
 * @param type the type of data structure to use a=avl tree, b=hash table, default to avl tree
 */
IndexHandler::IndexHandler(char type) {
    switch (type) {
        case 'a':
            _tree = new AVLTreeAdapter;
            break;
        case 'b':
            _tree = new HashTableAdapter;
            break;
        default:
            _tree = new AVLTreeAdapter;
    }
}

/**
 * Insert a term and return a pointer to the new term
 * @param term
 * @return ptr to term
 */
Term* IndexHandler::insert(string term) {

    Term* found = search(term);

    if (found != NULL) {
        //term is not in the index so add it
        Term* newTerm = new Term(term);
        found = newTerm;
        _tree->insert(newTerm);
    }

    return found;

}

/**
 * Return the term with a given index
 * @param query
 * @return pointer to the term 
 */
Term* IndexHandler::search(string query) {
    return _tree->search(query);
}

/**
 * Write the inverted file index to a file (uses the methods defined in the AVLTree and HashTable adapters)
 * @param filePath file to output to
 */
void IndexHandler::writeIndexToFile(string filePath) {
    ofstream outputFile(filePath);
    _tree->outputFile(outputFile);
}

/**
 * Read the inverted file index from a file and back into the data structure
 * @param filePath
 */
void IndexHandler::readIndexFromFile(string filePath) {

    //incomplete
}

/**
 * Output the results of an unparsed search query
 * @param query unparsed search query
 */
void IndexHandler::outputRawSearch(string query) {

    string substr = query.substr(0, 3);

    /*switch(substr){
        case "AN":
        {
            break;
        }
        case "OR":
        {
            break;
        }
        default:
        {
            
        }
    }*/

    Term* found = search(query);
    if (found != NULL) {
        cout << "Term found in:" << endl;
        map<int, int>* foundInDocuments = found->getDocumentOccurances();
        for (map<int, int>::iterator docit = foundInDocuments->begin(); docit != foundInDocuments->end(); ++docit) {
            cout << "Document " << docit->first <<endl;
        }
    }


}